import { http } from "@/utils/http";

export type UserResult = {
  success: boolean;
  data: {
    /** 用户名 */
    username: string;
    /** 当前登陆用户的角色 */
    roles: Array<string>;
    /** `token` */
    accessToken: string;
    /** 用于调用刷新`accessToken`的接口时所需的`token` */
    refreshToken: string;
    /** `accessToken`的过期时间（格式'xxxx/xx/xx xx:xx:xx'） */
    expires: Date;
    //
    systemFuncList?: FunctionMethod[];
  };
};

export type FunctionMethod = {
  categoryID: string;
  functionID: string;
  permission: "W" | "X";
  type: "interface" | "menu" | "button";
};

export type RefreshTokenResult = {
  success: boolean;
  data: {
    /** `token` */
    accessToken: string;
    /** 用于调用刷新`accessToken`的接口时所需的`token` */
    refreshToken: string;
    /** `accessToken`的过期时间（格式'xxxx/xx/xx xx:xx:xx'） */
    expires: Date;
  };
};

/** 登录 */
export const getLogin = (data?: object) => {
  return http.request<UserResult>("post", "/login", { data });
};

/** 刷新token */
export const refreshTokenApi = (data?: object) => {
  return http.request<RefreshTokenResult>("post", "/refreshToken", { data });
};

export const getUserInfoApi = (data?: object) => {
  return http.request<UserResult>(
    "post",
    "/api/mycim2plus/usersave?action=members&members=1",
    {
      data
    },
    {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded;",
        "Is-Struts": true
      }
    }
  );
};

export const userDetailSaveApi = (data?: any) => {
  const { urlParams, formData } = data;
  const urlParamsString = Object.entries(urlParams)
    .map(
      ([key, value]: [string, string]) =>
        `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
    )
    .join("&");
  return http.request<UserResult>(
    "post",
    `/api/mycim2plus/userdetailsave?${urlParamsString}`,
    {
      data: formData
    },
    {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded;",
        "Is-Struts": true
      }
    }
  );
};

// 查询用户group
export const searchActionApi = (data?: any) => {
  const { urlParams, formData } = data;
  const urlParamsString = Object.entries(urlParams)
    .map(
      ([key, value]: [string, string]) =>
        `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
    )
    .join("&");
  return http.request<UserResult>(
    "post",
    `/api/mycim2plus/searchAction.do?${urlParamsString}`,
    {
      data: formData
    }
  );
};
